package sample;

import javafx.application.Platform;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by Administrator on 2016/6/27.
 */
public class ConnectThread extends Thread {
    private final Socket mSocket;
    private OutputStream outputStream;
    private InputStream inputStream;
    private OnReceiverListener onReceiveTextListener;
    private boolean isFinish;

    public ConnectThread(Socket socket) {
        System.out.println("客户端已经接入" + socket.getInetAddress());
        this.mSocket = socket;
        try {
            outputStream = mSocket.getOutputStream();
            inputStream = mSocket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        byte[] buffer = new byte[1024];
        System.out.println("服务器开始准备读取数据");
        while (!isFinish) {
            try {
                int read = inputStream.read(buffer);
                if (read > 0 && onReceiveTextListener != null) {
                    Platform.runLater(() -> onReceiveTextListener.onReceive(mSocket.getInetAddress() + ":" + new String(buffer)));
                }
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    mSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public void setOnReceiveTextListener(OnReceiverListener onReceiveTextListener) {
        this.onReceiveTextListener = onReceiveTextListener;
    }

    public OnReceiverListener getOnReceiveTextListener() {
        return onReceiveTextListener;
    }

    public void sendText(String s) {
        try {
            if (outputStream != null) {
                outputStream.write(s.getBytes("UTF-8"));
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
